package net.yc.imalachat.push.assist;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.common.app.Application;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import net.yc.imalachat.push.R;
import net.yc.imalachat.push.media.GalleryFragment;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.view.View.GONE;

/**
 * 权限申请弹出框
 * implements EasyPermissions.PermissionCallbacks: 权限申请的回调
 */
public class PermissionsFragment extends BottomSheetDialogFragment implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = "PermissionsFragment";

    // 权限回调的标识
    private static final int RC = 0x0100;

    public PermissionsFragment() {
        // Required empty public constructor
    }

    @NonNull
    @NotNull
    @Override
    public Dialog onCreateDialog(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        // 直接复用
        return new GalleryFragment.TransStatusBottomSheetDialog(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 获取布局中的控件
        View root = inflater.inflate(R.layout.fragment_permissions, container, false);

        // 找到按钮
        root.findViewById(R.id.btn_submit)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 点击的时候进行申请权限
                        requestPermissions();
                    }
                });
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 界面显示的时候进行刷新
        refreshState(getView());
    }

    /**
     * 刷新我们布局中图片的状态
     * @param view 根布局
     */
    private void refreshState(View view) {
        if (view == null) {
            return;
        }
        Context mContext = getContext();
        view.findViewById(R.id.iv_state_permission_network).setVisibility(!haveNetwork(mContext) ? View.GONE : View.VISIBLE);
        view.findViewById(R.id.iv_state_permission_read).setVisibility(!haveReadPerm(mContext) ? View.GONE : View.VISIBLE);
        view.findViewById(R.id.iv_state_permission_write).setVisibility(!haveWritePerm(mContext) ? View.GONE : View.VISIBLE);
        view.findViewById(R.id.iv_state_permission_record_audio).setVisibility(!haveRecordAudioPerm(mContext) ? View.GONE : View.VISIBLE);
    }

    /**
     * 获取是否有网络权限
     * @param mContext 上下文
     * @return
     */
    private static boolean haveNetwork (Context mContext) {
        // 准备需要检查的网络的权限
        String[] permissions = new String[] {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE
        };
        // 检查权限是否有
        return EasyPermissions.hasPermissions(mContext, permissions);
    }

    /**
     * 获取是否有读取外部存储权限
     * @param mContext 上下文
     * @return
     */
    private static boolean haveReadPerm (Context mContext) {
        // 准备需要检查的读取的权限
        String[] permissions = new String[] {
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        // 检查权限是否有
        return EasyPermissions.hasPermissions(mContext, permissions);
    }

    /**
     * 获取是否有外部存储写入权限
     * @param mContext 上下文
     * @return
     */
    private static boolean haveWritePerm (Context mContext) {
        // 准备需要检查的写入的权限
        String[] permissions = new String[] {
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        // 检查权限是否有
        return EasyPermissions.hasPermissions(mContext, permissions);
    }

    /**
     * 获取是否有录音权限
     * @param mContext 上下文
     * @return
     */
    private static boolean haveRecordAudioPerm (Context mContext) {
        // 准备需要检查的录音的权限
        String[] permissions = new String[] {
                Manifest.permission.RECORD_AUDIO
        };
        // 检查权限是否有
        return EasyPermissions.hasPermissions(mContext, permissions);
    }

    /**
     * 私有的show方法
     * @param fm
     */
    private static void show(FragmentManager fm) {
        // 调用已经准备好的显示方法
        new PermissionsFragment()
                .show(fm, PermissionsFragment.class.getName());
    }

    /**
     * 检查是否具有所有的权限
     * @param mContext
     * @param fm FragmentManager
     * @return 是否有了权限，true ：有权限
     */
    public static boolean haveAllPerm(Context mContext, FragmentManager fm) {
        boolean allPerm = haveReadPerm(mContext) && haveReadPerm(mContext)
                            && haveRecordAudioPerm(mContext) && haveWritePerm(mContext);

        // 如果没有则显示当前申请权限的界面
        if (!allPerm) {
            show(fm);
        }

        return allPerm;
    }


    /**
     * 申请权限的方法
     * EasyPermissions.hasPermissions(String... perms)
     * @AfterPermissionGranted（RC）：这是标识的id，无论申请成功还是失败，都会回调到这个方法当中
     */
    @AfterPermissionGranted(RC)
    private void requestPermissions() {
        String[] permissions = new String[] {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
        };
        if (EasyPermissions.hasPermissions(getContext(), permissions)) {
            Application.showToast(R.string.label_permission_ok);
            Log.d(TAG, "requestPermissions: 授权成功");
            // 在fragment当中还可以直接通过getView()拿到根布局，前提是在onCreateView()方法之后
            refreshState(getView());
        } else {
            // 申请权限
            EasyPermissions.requestPermissions(this, getString(R.string.title_assist_permissions), RC, permissions);
        }

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull @NotNull List<String> perms) {

    }


    @Override
    public void onPermissionsDenied(int requestCode, @NonNull @NotNull List<String> perms) {
        // 如果权限中没有申请成功的权限在，则弹出弹出框，用户点击之后去到界面自己打开权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog
                    .Builder(this)
                    .build()
                    .show();
        }
    }

    /**
     * 权限申请的时候回调的方法，在这个方法中把对应的权限状态交给EasyPermissions框架
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 传递对应的参数并且告知接收权限的处理者是我自己
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}